package com.ourteam.system.api;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ourteam.frame.controller.AbstractServiceController;
import com.ourteam.frame.web.AbstractSearchHelper;
import com.ourteam.frame.web.AbstractStaticArraySearchHelper;
import com.ourteam.frame.web.AbstractTreeBuilderHelper;
import com.ourteam.frame.web.GridBean;
import com.ourteam.frame.web.TreeParamModel;
import com.ourteam.system.dao.SysRoleDAOQueryBean;
import com.ourteam.system.dao.SysRoleGroupDAOQueryBean;
import com.ourteam.system.dao.SysRoleRelateDAOQueryBean;
import com.ourteam.system.domain.SystemAction;
import com.ourteam.system.domain.SystemModule;
import com.ourteam.system.domain.SystemRole;
import com.ourteam.system.domain.SystemRoleGroup;
import com.ourteam.system.domain.SystemRoleGroupRelate;
import com.ourteam.system.domain.SystemUserRoleRelate;
import com.ourteam.system.service.ISysRoleService;
import com.ourteam.system.service.ISysUserService;

@Controller
@CrossOrigin
@RequestMapping("/api/SYSTEM/SYSROLE")
public class SystemRoleAPI extends AbstractServiceController {

	@Autowired
	private ISysRoleService sysRoleService;

	@Autowired
	private ISysUserService sysUserService;

	@RequestMapping("/querySysAccountNoRoleList")
	@ResponseBody
	public GridBean querySysAccountNoRoles(
			@RequestParam(value = "accountId", required = false, defaultValue = "0") long accountId,
			@ModelAttribute SystemRoleSearchModel searchModel, HttpServletRequest request, Model model)
			throws Exception {

		List<Long> sysRoleIds = new ArrayList<Long>();

		SystemUserRoleRelate[] userAuthorities = this.sysUserService.getSysUserAuthorities(accountId);

		for (int i = 0; i < userAuthorities.length; i++) {
			SystemUserRoleRelate systemUserRoleRelate = userAuthorities[i];
			if (systemUserRoleRelate.getRoleType().equals("ROLE")) {
				sysRoleIds.add(systemUserRoleRelate.getRoleId());
			}
		}

		searchModel.setExcludeIds(ArrayUtils.toPrimitive(sysRoleIds.toArray(new Long[sysRoleIds.size()])));

		return querySysRoles(searchModel, request, model);
	}

	@RequestMapping("/querySysAccountNoRoleGroupList")
	@ResponseBody
	public GridBean querySysAccountNoRoleGroupList(
			@RequestParam(value = "accountId", required = false, defaultValue = "0") long accountId,
			@ModelAttribute SystemRoleGroupSearchModel searchModel, HttpServletRequest request, Model model)
			throws Exception {

		List<Long> sysRoleGroupIds = new ArrayList<Long>();

		SystemUserRoleRelate[] userAuthorities = this.sysUserService.getSysUserAuthorities(accountId);

		for (int i = 0; i < userAuthorities.length; i++) {
			SystemUserRoleRelate systemUserRoleRelate = userAuthorities[i];
			if (systemUserRoleRelate.getRoleType().equals("ROLE_GROUP")) {
				sysRoleGroupIds.add(systemUserRoleRelate.getRoleId());
			}
		}

		searchModel.setExcludeIds(ArrayUtils.toPrimitive(sysRoleGroupIds.toArray(new Long[sysRoleGroupIds.size()])));

		return querySysRoleGroups(searchModel, request, model);
	}

	@RequestMapping("/querySysRoleGroupNoRoleList")
	@ResponseBody
	public GridBean querySysRoleGroupNoRoleList(
			@RequestParam(value = "roleGroupId", required = false, defaultValue = "0") long roleGroupId,
			@ModelAttribute SystemRoleSearchModel searchModel, HttpServletRequest request, Model model)
			throws Exception {

		SystemRoleGroupRelate[] systemRoleGroupRelates = sysRoleService.getSysRoleGroupRelatedRoles(roleGroupId);

		long[] sysRoleIds = new long[systemRoleGroupRelates.length];

		for (int i = 0; i < sysRoleIds.length; i++) {
			sysRoleIds[i] = systemRoleGroupRelates[i].getRelatedSysRoleId();

		}

		searchModel.setExcludeIds(sysRoleIds);

		return querySysRoles(searchModel, request, model);
	}

	@RequestMapping("/querySysRoleList")
	@ResponseBody
	public GridBean querySysRoles(@ModelAttribute SystemRoleSearchModel searchModel, HttpServletRequest request,
			Model model) throws Exception {

		AbstractSearchHelper<SysRoleDAOQueryBean, SystemRoleSearchModel> searchHelper = new AbstractSearchHelper<SysRoleDAOQueryBean, SystemRoleSearchModel>(
				searchModel) {

			@Override
			protected int queryCount(SysRoleDAOQueryBean queryBean) throws Exception {
				return sysRoleService.getSysRoleCount(queryBean);
			}

			@Override
			protected Object[] queryData(SysRoleDAOQueryBean queryBean) throws Exception {
				return sysRoleService.getSysRoles(queryBean);
			}

			@Override
			protected SysRoleDAOQueryBean createQueryBean() {
				return new SysRoleDAOQueryBean();
			}
		};

		return searchHelper.doSearch(request);

	}

	@RequestMapping("/querySysRoleGroupList")
	@ResponseBody
	public GridBean querySysRoleGroups(@ModelAttribute SystemRoleGroupSearchModel searchModel,
			HttpServletRequest request, Model model) throws Exception {

		AbstractSearchHelper<SysRoleGroupDAOQueryBean, SystemRoleGroupSearchModel> searchHelper = new AbstractSearchHelper<SysRoleGroupDAOQueryBean, SystemRoleGroupSearchModel>(
				searchModel) {

			@Override
			protected int queryCount(SysRoleGroupDAOQueryBean queryBean) throws Exception {
				return sysRoleService.getSysRoleGroupCount(queryBean);
			}

			@Override
			protected Object[] queryData(SysRoleGroupDAOQueryBean queryBean) throws Exception {
				return sysRoleService.getSysRoleGroups(queryBean);
			}

			@Override
			protected SysRoleGroupDAOQueryBean createQueryBean() {
				return new SysRoleGroupDAOQueryBean();
			}
		};

		return searchHelper.doSearch(request);

	}

	@RequestMapping("/saveSysRole")
	@ResponseBody
	public SystemRole saveSysRole(@ModelAttribute SystemRole systemRole, HttpServletRequest request, Model model)
			throws Exception {

		systemRole.setOperatorId(getLoginUserId());
		systemRole.setModifyTime(new Date());

		if (systemRole.getId() != 0) {
			this.sysRoleService.modifySysRole(systemRole);
		} else {
			this.sysRoleService.createSysRole(systemRole);
		}

		return systemRole;
	}

	@RequestMapping("/saveSysRoleGroup")
	@ResponseBody
	public SystemRoleGroup saveSysRoleGroup(@ModelAttribute SystemRoleGroup systemRoleGroup, HttpServletRequest request,
			Model model) throws Exception {

		systemRoleGroup.setOperatorId(getLoginUserId());
		systemRoleGroup.setModifyTime(new Date());

		if (systemRoleGroup.getId() != 0) {
			this.sysRoleService.modifySysRoleGroup(systemRoleGroup);
		} else {
			this.sysRoleService.createSysRoleGroup(systemRoleGroup);
		}

		return systemRoleGroup;
	}

	@RequestMapping("/getSysRoleById")
	@ResponseBody
	public SystemRole getSysRoleById(@RequestParam long id, HttpServletRequest request, Model model) throws Exception {

		return this.sysRoleService.getSysRoleById(id);
	}
	
	@RequestMapping("/getSysRoleByDomain")
	@ResponseBody
	public SystemRole[] getSysRoleByDomain(@RequestParam String domainCode, HttpServletRequest request, Model model) throws Exception {

		SysRoleDAOQueryBean queryBean = new SysRoleDAOQueryBean();
		
		queryBean.createCriteria().andDomainCodeEqualTo(domainCode);
		
		return this.sysRoleService.querySysRoles(queryBean);
	}

	@RequestMapping("/getSysRoleGroupById")
	@ResponseBody
	public SystemRoleGroup getSysRoleGroupById(@RequestParam long id, HttpServletRequest request, Model model)
			throws Exception {

		return this.sysRoleService.getSysRoleGroupById(id);
	}
	
	@RequestMapping("/deactiveSysRoles")
	@ResponseBody
	public String lockedSysAccount(@RequestParam(value = "ids[]") long[] ids, HttpServletRequest request, Model model)
			throws Exception {

		for (int i = 0; i < ids.length; i++) {
			
			SystemRole systemRole = this.sysRoleService.getSysRoleById(ids[i]);

			systemRole.setStatus("deactive");

			sysRoleService.modifySysRole(systemRole);
		}

		return "success";
	}

	@RequestMapping("/deleteSysRole")
	@ResponseBody
	public String deleteSysRoles(@RequestParam(value = "ids") long[] ids, HttpServletRequest request, Model model)
			throws Exception {

		for (int i = 0; i < ids.length; i++) {
			this.sysRoleService.deleteSysRole(ids[i], getLoginUserId());
		}

		return "success";
	}

	@RequestMapping("/deleteSysRoleGroup")
	@ResponseBody
	public String deleteSysRoleGroups(@RequestParam(value = "ids") long[] ids, HttpServletRequest request,
			Model model) throws Exception {

		for (int i = 0; i < ids.length; i++) {
			this.sysRoleService.deleteSysRoleGroup(ids[i], getLoginUserId());
		}

		return "success";
	}

	@RequestMapping("/getSysRoleGroupRelatedRoles")
	@ResponseBody
	public GridBean getSysRoleGroupRelatedRoles(@ModelAttribute SystemRoleRelateSearchModel searchModel,
			HttpServletRequest request) throws Exception {

		AbstractStaticArraySearchHelper<SysRoleRelateDAOQueryBean, SystemRoleRelateSearchModel> searchHelper = new AbstractStaticArraySearchHelper<SysRoleRelateDAOQueryBean, SystemRoleRelateSearchModel>(
				searchModel) {

			@Override
			protected SysRoleRelateDAOQueryBean createQueryBean() {
				return new SysRoleRelateDAOQueryBean();
			}

			@Override
			protected Object[] getData(SystemRoleRelateSearchModel searchModel) throws Exception {
				return sysRoleService.getSysRoleGroupRelatedRoles(searchModel.getRoleGroupId());
			}
		};

		return searchHelper.doSearch(request);
	}

	@RequestMapping("/getSysRolePurViewModules")
	@ResponseBody
	public GridBean getSysRolePurViewModules(@RequestParam final long roleId,
			@ModelAttribute TreeParamModel treeParamModel) throws Exception {

		final SystemRole systemRole = this.sysRoleService.getSysRoleById(roleId);

		SystemAppModuleTreeBuilder treeBuilder = new SystemAppModuleTreeBuilder(0);

		AbstractTreeBuilderHelper<SystemAppModuleTreeBuilder> treeBuilderHelper = new AbstractTreeBuilderHelper<SystemAppModuleTreeBuilder>(
				treeBuilder) {

			@Override
			protected Object getInitParameter() {
				return String.valueOf(systemRole.getDomainId());
			}

		};

		return treeBuilderHelper.buildTree(treeParamModel);
	}

	@RequestMapping("/addSysRoleGroupRoles")
	@ResponseBody
	public String addSysRoleGroupRoles(@RequestParam(value = "sysRoleGroupId") long sysRoleGroupId,
			@RequestParam(value = "sysRoleIds") String sysRoleIds, HttpServletRequest request, Model model)
			throws Exception {

		String[] roleIds = StringUtils.split(sysRoleIds, ",");

		SystemRoleGroupRelate[] addRoleGroupRelates = new SystemRoleGroupRelate[roleIds.length];

		for (int i = 0; i < addRoleGroupRelates.length; i++) {
			addRoleGroupRelates[i] = new SystemRoleGroupRelate();

			addRoleGroupRelates[i].setSysRoleGroupId(sysRoleGroupId);

			addRoleGroupRelates[i].setRelatedSysRoleId(Long.parseLong(roleIds[i]));
		}

		SystemRoleGroupRelate[] groupRelates = sysRoleService.getSysRoleGroupRelatedRoles(sysRoleGroupId);

		sysRoleService.setSysRoleGroupRelatedRoles(sysRoleGroupId,
				(SystemRoleGroupRelate[]) ArrayUtils.addAll(addRoleGroupRelates, groupRelates));

		return "success";
	}

	@RequestMapping("/removeSysRoleGroupRoles")
	@ResponseBody
	public String removeSysRoleGroupRoles(@RequestParam(value = "sysRoleGroupId") long sysRoleGroupId,
			@RequestParam(value = "sysRoleIds") String ids, HttpServletRequest request, Model model) throws Exception {

		String[] roleIds = StringUtils.split(ids, ",");

		List<SystemRoleGroupRelate> roleGroupRelates = new ArrayList<SystemRoleGroupRelate>();

		SystemRoleGroupRelate[] currentRoleGroupRelates = this.sysRoleService
				.getSysRoleGroupRelatedRoles(sysRoleGroupId);

		boolean canAdd = true;
		for (int i = 0; i < currentRoleGroupRelates.length; i++) {
			SystemRoleGroupRelate roleGroupRelate = currentRoleGroupRelates[i];
			for (int j = 0; j < roleIds.length; j++) {
				long id = Long.parseLong(roleIds[j]);
				if (roleGroupRelate.getId() == id) {
					canAdd = false;
					break;
				}
			}
			if (canAdd == true) {
				roleGroupRelates.add(roleGroupRelate);
			}

			canAdd = true;

		}

		sysRoleService.setSysRoleGroupRelatedRoles(sysRoleGroupId,
				roleGroupRelates.toArray(new SystemRoleGroupRelate[roleGroupRelates.size()]));

		return "success";
	}

	@RequestMapping("/getSysRoleModules")
	@ResponseBody
	public SystemModule[] getSysRoleModules(@RequestParam final long roleId,
			@ModelAttribute TreeParamModel treeParamModel) throws Exception {

		return sysRoleService.getSysRoleModules(new long[] { roleId });
	}

	@RequestMapping("/getSysRoleActions")
	@ResponseBody
	public SystemAction[] getSysRoleActions(@RequestParam final long roleId,
			@ModelAttribute TreeParamModel treeParamModel) throws Exception {

		return sysRoleService.getSysRoleActions(new long[] { roleId });
	}

	@RequestMapping("/saveSysRolePurView")
	@ResponseBody
	public String saveSysRolePurView(@RequestParam final long roleId,
			@RequestParam(value = "moduleIds") String moduleIds, @RequestParam(value = "actionIds") String actionIds)
			throws Exception {

		String[] moduleIdArray = StringUtils.split(moduleIds, ",");

		long[] sysModuleIds = new long[moduleIdArray.length];

		for (int i = 0; i < moduleIdArray.length; i++) {
			sysModuleIds[i] = Long.parseLong(moduleIdArray[i]);

		}

		String[] actionIdArray = StringUtils.split(actionIds, ",");

		long[] sysActionIds = new long[actionIdArray.length];

		for (int i = 0; i < actionIdArray.length; i++) {
			sysActionIds[i] = Long.parseLong(actionIdArray[i]);

		}

		sysRoleService.setSysRoleModules(roleId, sysModuleIds);

		sysRoleService.setSysRoleActions(roleId, sysActionIds);

		return "success";
	}
}
